/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package justdoit.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import justdoit.model.Task;

/**
 *
 * @author Rajalakshmi
 */
public class ReminderInitiator {

    private static String nextTask;
    private static Thread nextTaskThread;
    static String msg;

    public ReminderInitiator() {
        getNextTask();
    }

    //editing by Sadan
    private static void getNextTask() {
        List<Task> taskList = new ArrayList<Task>();
        taskList = TaskManager.getCurrentUser().getTasks();

        Date prevDate = null;
        Date nextDate = null;

        String prevDateStr = null;
        Task deleteTask = null;
        for (Task task : taskList) {
            Date reminderDate = task.getReminderDate().getTime();
            Date dueDate = task.getDueDate().getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = new Date();
            if (reminderDate.equals(now)) {
                System.out.print("reminder came");
            }
            if (dueDate.after(now)) {
                System.out.print("due date came");
                deleteTask = task;
            }
        }
//        for (Task task : taskList) {
//            try {
//                //String dateStr = task.getReminder();
//                Date reminderDate = task.getReminderDate().getTime();
//                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                if (prevDate == null) {
//                    prevDate = sdf.parse(reminderDate.toString());
//                    if (!prevDate.before(new Date())) {
//                        prevDateStr = reminderDate.toString();
//                    } else {
//                        prevDate = null;
//                    }
//                    deleteTask = task;
//                } else {
//                    nextDate = sdf.parse(reminderDate.toString());
//                    if (!nextDate.before(new Date()) && prevDate.after(nextDate)) {
//                        prevDate = nextDate;
//                        prevDateStr = reminderDate.toString();
//                        deleteTask = task;
//                    }
//                }
//
//            } catch (ParseException ex) {
//                Logger.getLogger(ReminderInitiator.class.getName()).log(Level.SEVERE, null, ex);
//            }
//
//        }

        if (prevDate != null) {
            nextTask = prevDateStr;
            msg = deleteTask.getDescription();
            taskList.remove(deleteTask);

        }

//       nextTask = prevDate.toString();


        if (nextTask != null) {
            nextTaskThread = new Thread(new TaskScheduler());
            nextTaskThread.start();

            try {
                nextTaskThread.join();
               
            } catch (InterruptedException ex) {
                Logger.getLogger(ReminderInitiator.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    private static class TaskScheduler implements Runnable {

        /**
         * What the thread runs in order to create
         * the next reminder that is on Deck.
         */
        public void run() {

            System.out.println("RUNNNN" + msg);
            Calendar reminderDate = getCalendarFromString(nextTask);
            long sleepTime = reminderDate.getTimeInMillis() - Calendar.getInstance().getTimeInMillis()
                    - (Calendar.getInstance().get(Calendar.SECOND) * 1000);
            try {
                //Pause till next reminder time
                System.out.println("Thread is sleeping" + msg);

                Thread.sleep(sleepTime);
                System.out.println("Thread woke" + msg);
                JOptionPane.showMessageDialog(null, "Time for the Reminder : " + msg, "Reminder", JOptionPane.INFORMATION_MESSAGE);
                getNextTask();
            } catch (InterruptedException e) {
            }
        }
    }

    public static Calendar getCalendarFromString(String dateString) {
        GregorianCalendar calendar = new GregorianCalendar();
        if (dateString.equalsIgnoreCase("")) {
            calendar.clear();
            return calendar;
        }
        String[] date = dateString.split("/");
        calendar.set(Integer.parseInt(date[2]),
                Integer.parseInt(date[0]) - 1, Integer.parseInt(date[1]),
                Integer.parseInt(date[3]), Integer.parseInt(date[4]));
        return calendar;
    }
}
